<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Repos\OrderRepo;
use App\Models\AdminCate;
use App\Models\Admin;
use App\Models\OrderDispatch;
use App\Models\OrderProduct;
use App\Models\Order;

class IndexController extends Controller
{       
    // 进行中的订单
    public function orderList(Request $request)
    {
        // 根据openid 获取 admin_id,
        // 根据admin_id,查询负责的cate_id;
        // 根据 cate_id 确定订单order_id
        $wxUser = session('wechat.oauth_user.default');
        $openid = $wxUser->id;
        $admin     = Admin::where(['openid'=>$openid])->first();
        $cate_ids  = AdminCate::where('admin_id',$admin->id)
                              ->pluck('cate_id');
        $order_ids = OrderProduct::whereIn('product_cate_id',$cate_ids)
                                 ->pluck('order_id');
        $list = Order::whereIn('id',$order_ids)
                       ->whereIn('status',['2','3','4','5'])
                       ->paginate(10);
        return view('h5.order-index',compact('list'));                                               

    }

    public function orderInfo(Request $request)
    {
    	$where['id'] = $request->order_id;
    	$order  = OrderRepo::find($where);   	
    	
    	$view   = 'h5.order-info';
    	$admins = [];
    	if($request->cate_id) {
    		$view = 'h5.order-dispatch';
    		$acWhere['product_cate_id'] = $request->cate_id;
    		$admins = AdminCate::where($acWhere)->get();	
    	}
    	
    	return view($view,compact('order','admins'));
    }

    public function orderDispatch(Request $request)
    {
    	$data = $request->except(['_token']);
        $admin_ids = $data['admin_id'];
        foreach ($admin_ids as $k => $v) {
            $order['order_id'] = $data['order_id'];
            $order['admin_id'] = $v;
            OrderDispatch::create($order);
        }

        // 订单状态改为4 已派工
        $order = OrderRepo::find($data['order_id']);
        $order->status = 4;
        $order->save();

        // 通知护士


    }

    // 护士接单
    public function orderAccept(Request $request)
    {   
        $data['order_id'] = $request->order_id;
        $order = OrderRepo::confirm($data['order_id']);
        
        return back();


    }


}
